package site.teamo.biu.flink.web.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ssh.JschUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import site.teamo.biu.flink.common.enums.ExecutionEngineType;
import site.teamo.biu.flink.web.entity.ExecutionEngineDO;
import site.teamo.biu.flink.web.entity.executionengine.ExecutionEngineContentDO;
import site.teamo.biu.flink.web.entity.executionengine.ExecutionEngineLocalContentDO;
import site.teamo.biu.flink.web.exception.BiuResponseCode;
import site.teamo.biu.flink.web.mapper.ExecutionEngineMapper;
import site.teamo.biu.flink.web.service.ExecutionEngineService;

import java.nio.charset.Charset;

/**
 * @author haocongshun
 * @date 2023/11/03 15:26:25
 */
@Service
@Slf4j
public class ExecutionEngineServiceImpl extends ServiceImpl<ExecutionEngineMapper, ExecutionEngineDO> implements ExecutionEngineService {

    @Override
    public boolean createEngine(String name, ExecutionEngineType type, JSONObject content) {
        if (ExecutionEngineType.LOCAL.equals(type)) {
            ExecutionEngineLocalContentDO localContent = JSON.parseObject(content.toJSONString(), ExecutionEngineLocalContentDO.class);
            Session session = null;
            try {
                session = JschUtil.getSession(
                        localContent.getHost(),
                        localContent.getPort(),
                        localContent.getUsername(),
                        localContent.getPassword());
                String javaVersion = JschUtil.exec(session, localContent.getJavaHome() + "/bin/java -version 2>&1 | grep -oP '\\\"[^\\\"]*\\\"'", Charset.defaultCharset());
                if (StrUtil.isBlank(javaVersion.trim())) {
                    throw BiuResponseCode.GENERAL_ERROR.runtimeException("未检测到java版本");
                }
                JschUtil.exec(session, "mkdir -p " + localContent.getWorkspace(), Charset.defaultCharset());
            } finally {
                if (session != null) {
                    JschUtil.close(session);
                }
            }
        }
        return save(new ExecutionEngineDO()
                .setName(name)
                .setType(type)
                .setContent(content.toJSONString())
        );
    }
}
